import { useState, useContext,useEffect } from 'react';
import { Button, Form, Input, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import {
  STORAGE_LANG_KEY, STORAGE_USERINFO_KEY, STORAGE_USERINFO_VALID_TIME_KEY,
  STORAGE_USERINFO_USER_MENUS, STORAGE_USERINFO_USER_PATH_MENUS,
} from '@/utils/constants/index';
import { useTranslation } from 'react-i18next';
import { useRouter } from 'next/router';
import { authLogin, query_user_info, query_user_menus } from '@/client/api/login';
import { RouteConfig } from '@/types/router';
import Image from 'next/image';
import { ChatContext } from '@/app/chat-context';
import { v4 as uuid } from 'uuid';
import { getParam } from '@/utils';
import { menus } from '@/client/api/login/menus' // mock  菜单数据

const LoginForm = (props: any) => {
  const {
    handleUserInfoChange,
  } = useContext(ChatContext);

  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const token = getParam('token')
  const [goldMimeToken] = useState(token);

  const router = useRouter();
  const modifyPaths = (menuList: any[]) => {
    if (!menuList?.length) return [];

    return menuList.map(menu => {
      let newPath = menu.path;
      if (newPath === '/construct') {
        newPath = '/construct/app';
      } else if (newPath === '/system') {
        newPath = '/system/user';
      }

      const newMenu = { ...menu, path: newPath };

      if (menu.children?.length) {
        newMenu.children = menu.children.map((child: any) => {
          let childPath = child.path;
          if (childPath.startsWith('/construct/')) {
            childPath = childPath.replace('/construct/', '/');
          } else if (childPath.startsWith('/system/')) {
            childPath = childPath.replace('/system/', '/');
          }
          return { ...child, path: childPath };
        });
      }

      return newMenu;
    });
  }
  const extractPaths = (routes: RouteConfig, basePath: null | string = null): string[] => {
    let paths: string[] = [];
    for (const route of routes) {
      if (basePath == '/construct/app') {
        route.path = '/construct' + route.path;
      }else if (basePath === '/system/user') {
        route.path = '/system' + route.path;
      }
      paths.push(route.path);
      if (route?.children?.length) {
        paths = paths.concat(extractPaths(route.children, route.path));
      }
    }
    const uniqueArray = [...new Set(paths)];
    return uniqueArray;
  };
  // 登录
  const onFinish = async (loginForm: any) => {
    try {
      setLoading(true);

      if(!loginForm.login_name || !loginForm.password) {
        return;
      }
      
      const params = {
        ...loginForm,
        method: "0",
        platform: "0"
      }
      const userInfo = await authLogin(params);
      if (userInfo?.data?.code == 200 && userInfo?.data?.data) {
        // const user = {
        //   user_channel: `dbgpt`,
        //   user_no: `001`,
        //   nick_name: `Noah`,
        // };
        const user = userInfo.data.data;
        if (user) {
          localStorage.setItem(STORAGE_USERINFO_KEY, JSON.stringify(user));
          localStorage.setItem(STORAGE_USERINFO_VALID_TIME_KEY, Date.now().toString());
          handleUserInfoChange(JSON.stringify(user));
          const user_menus = await query_user_menus();
          const user_menus_data = modifyPaths(user_menus?.data?.data); //modifyPaths(menus) // 

          localStorage.setItem(STORAGE_USERINFO_USER_MENUS, JSON.stringify(user_menus_data));
          localStorage.setItem(STORAGE_USERINFO_USER_PATH_MENUS, JSON.stringify(extractPaths(user_menus_data)));


          if (user_menus_data?.length) {
            const redirect = user_menus_data.find(i => i.path == '/home');
            let path = user_menus_data[0].path;
            if (path == '/construct') {
              path = '/construct/app';
            } else if (path == '/system') {
              path = '/system/user';
            }
            router.push(redirect?.path || path);
          }
          message.success('登录成功！');
        }
      } else {
        message.error(userInfo?.data?.msg || userInfo?.data?.message || '登录失败');
      }

    } finally {
      setLoading(false);
    }
  };

  const changeLoginPage = () => {
    const goldMineLoginUrl = `http://192.168.1.163:8000/login/oauth/authorize?response_type=code&client_id=77ab47d7a4cc0b0efb28&redirect_uri=${location.origin}/auth/oauth2/login`;

    window.open(goldMineLoginUrl, '_self');
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const handleAuth = async () => {
    try {
      setLoading(true);
      // goldmine 免登录    
      if(goldMimeToken){
        localStorage.setItem(STORAGE_USERINFO_KEY, JSON.stringify({access_token:goldMimeToken}));
        const userinfoRes = await query_user_info({});
        const user: any = userinfoRes?.data?.data;
        if (user) {
          localStorage.setItem(STORAGE_USERINFO_KEY, JSON.stringify({...user,access_token:goldMimeToken}));
          localStorage.setItem(STORAGE_USERINFO_VALID_TIME_KEY, Date.now().toString());
          handleUserInfoChange(JSON.stringify({...user,access_token:goldMimeToken}));
        }
        const user_menus = await query_user_menus();
        const user_menus_data = modifyPaths(user_menus?.data?.data);
        localStorage.setItem(STORAGE_USERINFO_USER_MENUS, JSON.stringify(user_menus_data));
        localStorage.setItem(STORAGE_USERINFO_USER_PATH_MENUS, JSON.stringify(extractPaths(user_menus_data)));
  
        if (user_menus_data?.length) {
          const redirectUrl = getParam('url');
          
          if(redirectUrl){
            if(redirectUrl.indexOf('http') == -1){
               router.push('/moreAnalysis_setting');
            }else{
              window.location.href = redirectUrl;
            }
          }else{
            const redirect = user_menus_data.find(i => i.path == '/home');
            let path = user_menus_data[0].path;
            if (path == '/construct') {
              path = '/construct/app';
            } else if (path == '/system') {
              path = '/system/user';
            }
            router.push(redirect?.path || path);
          }
        }
  
      }
    }  finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    if (goldMimeToken) {
      handleAuth();
    }
  }, [goldMimeToken,router.pathname]);

  return (
    <div className='relative' style={{ height: '100vh',padding:50 }}>
      { goldMimeToken ? null : (<>
        <video className="absolute top-0 left-0 w-full h-full object-cover"
                  autoPlay
                  loop
                  muted
                  playsInline>
          <source src="/universe-video.mp4" type="video/mp4"></source>
        </video>
        
        <div className='absolute top-0 left-0 w-full h-full rounded-xl p-[10%] flex justify-end items-center'>
          <Form className='px-20 py-8 rounded-xl bg-[rgba(255,255,255,0.2)] shadow-[0_0_12px_rgba(0,0,0,0.1)]'
            form={form}
            name='basic'
            labelCol={{ span: 5 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            size='large'
            autoComplete='off'
          >
            <div className='text-center mb-20 text-2xl' style={{
              backgroundImage: 'linear-gradient(90deg, #8665FF,white)', 
              backgroundClip: 'text', 
              color: 'transparent',
              fontStyle: 'italic',
              fontWeight:'bold',
              letterSpacing: 5
            }}>欢迎来到NoahX</div>
            <Form.Item name='login_name' rules={[{ required: true, message: '请输入用户名' }]}>
              <Input placeholder='用户名' prefix={<UserOutlined />} className='bg-[rgba(255,255,255,0.5)] border-0' style={{width:350}} />
            </Form.Item>
            <Form.Item name='password' rules={[{ required: true, message: '请输入密码' }]} className='w-350'>
              <Input.Password autoComplete='new-password' placeholder='密码' className='bg-[rgba(255,255,255,0.5)] border-0' prefix={<LockOutlined />} style={{width:350}} />
            </Form.Item>
            <Form.Item className='login-btn'>
              <Button style={{background:'#8665FF',border:0,color:'white'}} variant="solid" htmlType='submit' loading={loading} icon={<UserOutlined />} className='w-full'>
                登录
              </Button>
            </Form.Item>
            <div className='text-right text-sm text-white underline cursor-pointer' onClick={changeLoginPage}>
              用GoldMine账号登录
            </div>
            <div className='flex justify-center items-center' style={{marginTop:100}}>
              <Image src="/ai/welcome-dark.png" alt="login" width={270} height={50} />
            </div>
          </Form>
        </div>
      </>) }
    </div>
  );
};

export default LoginForm;
